local extension = Package:new("shanheyuzhui")

extension.extensionName = "hanjin"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["shanheyuzhui"] = "山河欲坠",
}

local hj_yuquan = General:new(extension, "hj__yuquan","wu", 4)

local hj_jueyong = fk.CreateTriggerSkill{
  name = "hj_jueyong",
  anim_type = "offensive",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    local typesRecorded = player:getTableMark("@[cardtypes]hj_jueyong-lable-turn")
    return target == player and player:hasSkill(self) and 
      table.every(player:getCardIds("h"),function (element, index, array)
        return data.card.type ~= Fk:getCardById(element).type
      end) and 
      table.every(typesRecorded,function (element, index, array)
        return data.card.type ~= element
    end)
  end,
  on_cost = function(self, event, target, player, data)
    local choices = table.filter(player.room:getOtherPlayers(player),function (element, index, array)
      return element:inMyAttackRange(player) and not element:isNude()
    end)
    self.cost_data = choices
    return #choices > 0 and player.room:askForSkillInvoke(player,self.name,data,"#hj_jueyong-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local typesRecorded = player:getTableMark("@[cardtypes]hj_jueyong-lable-turn")
    table.insertIfNeed(typesRecorded, data.card.type)
    player.room:setPlayerMark(player, "@[cardtypes]hj_jueyong-lable-turn", typesRecorded)
    local room = player.room
    for _ = 1, 2, 1 do
      if player.dead then return end
      local targets = table.map(table.filter(self.cost_data, function(p)
        return not p:isNude() end), Util.IdMapper)
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#hj_jueyong-choose", self.name, true)
      if #tos == 0 then return end
      local to = room:getPlayerById(tos[1])
      room:doIndicate(player.id, tos)
      local card = room:askForCardChosen(player, to, "he", self.name)
      room:throwCard({card}, self.name, to, player)
    end
  end,
}

local hj_sijie = fk.CreateTriggerSkill{
  name = "hj_sijie",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.BeforeCardsMove},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    for _, move in ipairs(data) do
      if move.from == player.id and move.to and move.to ~= player.id and move.moveReason == fk.ReasonPrey then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
  end,
  on_use =function (self, event, target, player, data)
    if not player:isKongcheng() then
      player:showCards(player.player_cards[Player.Hand])
    end
    local cards = 0
    for _, move in ipairs(data) do
      if move.from == player.id and move.to and move.to ~= player.id and move.moveReason == fk.ReasonPrey then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerHand then
            cards = cards + 1
          end
        end
      end
      move.moveInfo = {}
    end
    player.room:askForDiscard(player,cards,cards,true,self.name,false)
  end
}
hj_yuquan:addSkill(hj_jueyong)
hj_yuquan:addSkill(hj_sijie)

Fk:loadTranslationTable{
  ["hj__yuquan"] = "于诠",
  ["#hj__yuquan"] = "孤城忠魂",
  ["designer:hj__yuquan"] = "昼",
  ["hj_jueyong"] = "绝勇",
  [":hj_jueyong"] = "你使用牌后，若你手牌中没有此类型的牌，你依次弃置攻击范围内包含你的至多两名其他角色的共计至多两张牌。",
  ["#hj_jueyong-choose"] = "绝勇：弃置攻击范围包含你的一名角色的一张牌",
  ["@[cardtypes]hj_jueyong-lable-turn"] = "绝勇",
  ["#hj_jueyong-invoke"] = "是否发动“绝勇”依次弃置攻击范围内包含你的至多两名其他角色的共计至多两张牌？",
  ["hj_sijie"] = "死节",
  [":hj_sijie"] = "锁定技，其他角色获得你的牌改为你弃置等量的牌",
}

local hj_guanqiujian = General:new(extension, "hj__guanqiujian","wei", 4)

local hj_weizheng = fk.CreateTriggerSkill{
  name = "hj_weizheng",
  events = {fk.TurnStart},
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target == player
  end,
  on_cost = function (self, event, target, player, data)
    local target,cards = player.room:askForChooseCardsAndPlayers(player,1,999,table.map(player.room:getOtherPlayers(player),
    Util.IdMapper),1,1,nil,"#hj_weizheng-choose")
    if #target > 0 and cards then
      self.cost_data = {target[1], cards}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local n = 0
    for _,value in ipairs(self.cost_data[2]) do
      if Fk:getCardById(value).color == Card.Red then
        n = n+1
      end
    end
    player.room:addPlayerMark(player.room:getPlayerById(self.cost_data[1]),"@hj_weizheng-extraSlash-turn",n)
    player.room:recastCard(self.cost_data[2],player,self.name)
  end
}

local hj_weizheng_extraSlash = fk.CreateTriggerSkill{
  name = "#hj_weizheng_extraSlash",
  mute = true,
  main_skill = hj_weizheng,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill("hj_weizheng") and data.card and data.card.trueName == "slash" then
      local to = player.room:getPlayerById(data.to)
      return to:getMark("@hj_weizheng-extraSlash-turn") > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:addCardUseHistory(data.card.trueName, -1)
    room:removePlayerMark(room:getPlayerById(data.to), "@hj_weizheng-extraSlash-turn", 1)
  end,
}

local hj_genchu = fk.CreateTriggerSkill {
  name = "hj_genchu",
  anim_type = "drawcard",
  events = { fk.AfterCardsMove, fk.Damage },
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.AfterCardsMove and player:getMark("UseSkillMark") > 0 then
      self.cost_data = {}
      for _, move in ipairs(data) do
        if move.from and move.toArea == Card.DiscardPile and move.skillName == "dismantlement_skill" and move.proposer == player.id then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).type == Card.TypeBasic and player.room:getCardArea(info.cardId) == Card.DiscardPile then
              table.insertIfNeed(self.cost_data, info.cardId)
            end
          end
        end
      end
      if #self.cost_data > 0 then
        return true
      end
    else
      return target == player and data.to and not data.to.dead and data.to ~= player and data.from == player
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      return true
    else
      local card = player.room:askForCard(player,1,1,true,self.name,true,".","#hj_genchu-useCard:::"..target.id)
      if #card > 0 then
        self.cost_data = card
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      room:delay(200)
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(self.cost_data)
      room:obtainCard(player.id, dummy, true, fk.ReasonJustMove)
    else
      room:addPlayerMark(player,"UseSkillMark")
      room:useVirtualCard("dismantlement",self.cost_data,player,{target},self.name)
      room:setPlayerMark(player,"UseSkillMark",0)
    end
  end,
}

local hj_huizheng = fk.CreateTriggerSkill{
  name = "hj_huizheng",
  events = {fk.TurnEnd},
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if player:hasSkill(self) then
      return target == player and table.find(player.player_cards[Player.Hand], function (id)
        return Fk:getCardById(id):getMark("@@hj_huizheng-inhand") > 0
      end)
    end
  end,
  frequency = Skill.Compulsory,
  on_use = function (self, event, target, player, data)
    local cards = table.filter(player.player_cards[Player.Hand], function (id)
      return Fk:getCardById(id):getMark("@@hj_huizheng-inhand") > 0
    end)
    player.room:askForYiji(player,cards,player.room:getOtherPlayers(player),self.name,#cards,nil,nil)
  end,
  refresh_events = {fk.AfterCardsMove, fk.AfterTurnEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      return player:hasSkill(self, true) and player.phase ~= Player.Draw
    else
      table.find(player.player_cards[Player.Hand], function (id)
        return Fk:getCardById(id):getMark("@@hj_huizheng-inhand") > 0
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Player.Hand then
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if room:getCardArea(id) == Card.PlayerHand and room:getCardOwner(id) == player then
              room:setCardMark(Fk:getCardById(id), "@@hj_huizheng-inhand", 1)
            end
          end
        end
      end
    elseif event == fk.AfterTurnEnd then
      for _, id in ipairs(player:getCardIds(Player.Hand)) do
        room:setCardMark(Fk:getCardById(id), "@@hj_huizheng-inhand", 0)
      end
    end
  end,
}
local hj_huizheng_maxcards = fk.CreateMaxCardsSkill{
  name = "#hj_huizheng_maxcards",
  exclude_from = function(self, player, card)
    return card:getMark("@@hj_huizheng-inhand") > 0
  end,
}

hj_weizheng:addRelatedSkill(hj_weizheng_extraSlash)
hj_huizheng:addRelatedSkill(hj_huizheng_maxcards)
hj_guanqiujian:addSkill(hj_weizheng)
hj_guanqiujian:addSkill(hj_genchu)
hj_guanqiujian:addSkill(hj_huizheng)

Fk:loadTranslationTable{
  ["hj__guanqiujian"] = "毌丘俭",
  ["#hj__guanqiujian"] = "累战每慧",
  ["designer:hj__guanqiujian"] = "青",
  ["hj_weizheng"] = "威征",
  [":hj_weizheng"] = "回合开始时，你可以重铸任意张牌并选择一名其他角色，本回合你对其使用的前X张【杀】无次数限制（X为重铸的红牌数）。",
  ["#hj_weizheng-choose"] = "威征：你可以重铸任意张牌并选择一名其他角色，本回合你对其使用的前X张【杀】无次数限制（X为重铸的红牌数）。",
  ["@hj_weizheng-extraSlash-turn"] = "威征",
  ["hj_genchu"] = "根除",
  [":hj_genchu"] = "当你对其他角色造成伤害后，你可以将一张牌当【过河拆桥】对其使用，然后你获此过程中弃置的基本牌。",
  ["#hj_genchu-ask"] = "根除：是否对%src使用【过河拆桥】",
  ["hj_genchu_viewas"] = "根除  ",
  ["hj_huizheng"] = "慧正",
  [":hj_huizheng"] = "锁定技，你于摸牌阶段外获得的牌不计入手牌上限。你的回合结束时，你将这些牌分配给其他角色。",
  ["@@hj_huizheng-inhand"] = "慧正"
}


local hj__zhangrang = General:new(extension, "hj__zhangrang","qun", 3)

local hj_taoluan = fk.CreateActiveSkill{
  name = "hj_taoluan",
  frequency = Skill.Limited,
  target_filter = Util.FalseFunc,
  target_num = 0,
  card_filter = Util.FalseFunc,
  card_num = 0,
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name,Player.HistoryGame) == 0
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = room:getOtherPlayers(player)
    local choices = {"hj_taoluan-choice1","hj_taoluan-choice2"}
    local slash = Fk:cloneCard("ice__slash")
    slash.skillName = self.name
    for index, value in ipairs(targets) do
      if player.dead then
        room:useVirtualCard("ex_nihilo",nil,value,{value},self.name)
      else
        if not value:canUseTo(slash, player, { bypass_times = true, bypass_distances = true }) then
          room:useVirtualCard("ex_nihilo",nil,value,{value},self.name)
          room:askForYiji(value,nil,{player},self.name,2,2,"hj_taoluan-giveCard")
        end
        local r = room:askForChoice(value,choices,self.name,"hj_taoluan-AskChoices")
        if r == choices[1] then
          room:useVirtualCard("ice__slash",nil,value,{player})
        else
          room:useVirtualCard("ex_nihilo",nil,value,{value},self.name)
          room:askForYiji(value,nil,{player},self.name,2,2,"hj_taoluan-giveCard")
        end
      end
    end
  end
}

local hj_zhuofa = fk.CreateTriggerSkill{
  name = "hj_zhuofa",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetConfirmed,fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EnterDying then
      return player:hasSkill(self) and target ~= player 
      and target.maxHp > player.maxHp
      and player:usedSkillTimes("hj_taoluan",Player.HistoryGame)>0 
      and player:getMark("hj_zhuofa_turn-turn") == 0
    end
    if target == player and player:hasSkill(self) then
      local room = player.room
      local from = room:getPlayerById(data.from)
      if room.current ~= from then
        return false
      end
      if not from or from.dead or from.maxHp <= player.maxHp then return false end
      local mark = player:getMark("hj_zhuofa_record-turn")
      local use_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
      if use_event == nil then return false end
      if mark == 0 then
        room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
          local use = e.data[1]
          if table.contains(TargetGroup:getRealTargets(use.tos), player.id) then
            mark = e.id
            room:setPlayerMark(player, "hj_zhuofa_record-turn", mark)
            return true
          end
        end, Player.HistoryTurn)
      end
      return mark == use_event.id
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.TargetConfirmed then
      table.insertIfNeed(data.nullifiedTargets, player.id)
    else
      player:setSkillUseHistory("hj_taoluan",0,Player.HistoryGame)
      player.room:addPlayerMark(player,"hj_zhuofa_turn-turn",1)
    end
  end,
}

hj__zhangrang:addSkill(hj_taoluan)
hj__zhangrang:addSkill(hj_zhuofa)


Fk:loadTranslationTable{
  ["hj__zhangrang"] = "张让",
  ["#hj__zhangrang"] = "窃幸绝禋",
  ["designer:hj__zhangrang"] = "撕揉纸团",
  ["hj_taoluan"] = "滔乱",
  [":hj_taoluan"] = "限定技，出牌阶段你可以令所有其他角色选择一项：1、视为对你使用一张冰【杀】；2、视为使用一张【无中生有】然后交给你两张牌。",
  ["hj_taoluan-choice1"] = "视为对张让使用冰【杀】",
  ["hj_taoluan-choice2"] = "视为使用【无中生有】然后交给张让两张牌",
  ["hj_taoluan-giveCard"] = "将两张牌交给张让",
  ["hj_taoluan-AskChoices"] = "滔乱：请选择一项",
  ["$hj_taoluan1"] = "滔乱天常，侵夺朝威",
  ["$hj_taoluan2"] = "天下滔乱，正宜专权",
  ["hj_zhuofa"] = "浊伐",
  [":hj_zhuofa"] = "锁定技，你每回合第一次成为当前回合角色使用牌的目标后，若你的体力上限小于其，此牌对你无效。你每回合首次令体力上限大于你的角色进入濒死状态时，“滔乱”视为未发动过。"
}

local hj__sundeng = General:new(extension, "hj__sundeng","wu", 3)

local hj_tuohai = fk.CreateTriggerSkill{
  name = "hj_tuohai",
  anim_type = "support",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target==player and player:usedSkillTimes(self.name,Player.HistoryTurn) == 0
  end,
  on_cost = function (self, event, target, player, data)
    local target = player.room:askForChoosePlayers(player,table.map(player.room:getOtherPlayers(player),Util.IdMapper),1,1,"#hj_tuohai-chooseTarget",self.name)
    if target and #target>0 then
      self.cost_data = player.room:getPlayerById(target[1])
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local choice = player.room:askForSkillInvoke(self.cost_data,self.name,nil,"#hj_tuohai-choose2get")
    if choice then
      player.room:loseHp(self.cost_data,1,self.name)
      player.room:obtainCard(self.cost_data,data.card,true,fk.ReasonDraw)
    else
      player.room:drawCards(player,2,self.name)
    end
  end
}

local hj_xingguo = fk.CreateTriggerSkill{
  name = "hj_xingguo",
  events = {fk.AfterCardsMove,fk.DrawNCards},
  can_trigger = function (self, event, target, player, data)
    if event == fk.DrawNCards then
      return target:getMark("hj_xingguo-cards")> 0
    else
      if player:hasSkill(self) and player:getMark("xingguo-turn") == 0 then
        for _, move in ipairs(data) do
          if move.to and move.to == player.id and move.toArea == Player.Hand and player.phase ~= Player.Draw then
            return true
          end
        end
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.DrawNCards then
      return true
    else
      local max_cardnum = player.hp - player:getHandcardNum();
      if max_cardnum < 0 then
        max_cardnum = -max_cardnum
      end
      if max_cardnum == 0 then
        max_cardnum = 1
      end
      local room = player.room
      local targets,cards,choose = room:askForChooseCardsAndPlayers(player,1,max_cardnum,
        table.map(room:getAlivePlayers(),Util.IdMapper),1,1,'.',"#hj_xingguo-use:::"..tostring(max_cardnum),true)
      if choose then
        self.cost_data = {}
        self.cost_data.target = Util.Id2PlayerMapper(targets[1])
        self.cost_data.cards = cards
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.DrawNCards then
      data.n = data.n+target:getMark("hj_xingguo-cards")
      room:setPlayerMark(player,"hj_xingguo-cards",0)
    else
      room:addPlayerMark(player,"xingguo-turn")
      room:throwCard(self.cost_data.cards,self.name,player,player)
      room:addPlayerMark(self.cost_data.target,"hj_xingguo-cards",#self.cost_data.cards)
      room:addPlayerMark(self.cost_data.target,"@@hj_xingguo",1)
      if self.cost_data.target == player then
        room:loseHp(player,1,self.name)
      end
    end
  end
}

local hj_xingguo_record = fk.CreateTriggerSkill{
  name = "#hj_xingguo_record",
  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return player:getMark("@@hj_xingguo") > 0 and target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player,"@@hj_xingguo-turn",player:getMark("@@hj_xingguo"))
    room:addPlayerMark(player, MarkEnum.AddMaxCardsInTurn, player:getMark("@@hj_xingguo"))
    room:setPlayerMark(player,"@@hj_xingguo",0)
  end,
}

local hj_xingguo_targetmod = fk.CreateTargetModSkill{
  name = "#hj_xingguo_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@@hj_xingguo-turn") > 0 and scope == Player.HistoryPhase then
      return player:getMark("@@hj_xingguo-turn")
    end
  end,
}

local hj_xuanhe = fk.CreateTriggerSkill{
  name = "hj_xuanhe$",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player.phase == Player.Play and target == player and player:hasSkill(self)
  end,
  frequency = Skill.Compulsory,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local kingdom_wu = 0;
    local room = player.room;
    for index, value in ipairs(room:getAlivePlayers()) do
      if value.kingdom == "wu" then
        room = room+1
      end
    end
    if player:getHandcardNum() <= kingdom_wu then
      if not player:hasSkill("zhiheng") then
        room:handleAddLoseSkills(player,"zhiheng",self.name)
      end
    else
      if player:hasSkill("zhiheng") then
        room:handleAddLoseSkills(player,"-zhiheng",self.name)
      end
    end
    if player:getHandcardNum() >= kingdom_wu then
      if not player:hasSkill("jiang") then
        room:handleAddLoseSkills(player,"jiang",self.name)
      end
    else
      if player:hasSkill("jiang") then
        room:handleAddLoseSkills(player,"-jiang",self.name)
      end
    end
  end
}

hj__sundeng:addSkill(hj_tuohai)

hj_xingguo:addRelatedSkill(hj_xingguo_record)
hj_xingguo:addRelatedSkill(hj_xingguo_targetmod)
hj__sundeng:addSkill(hj_xingguo)

hj__sundeng:addSkill(hj_xuanhe)

Fk:loadTranslationTable{
  ["hj__sundeng"] = "孙登",
  ["#hj__sundeng"] = "入海蛟龙",
  ["designer:hj__sundeng"] = "",
  ["hj_tuohai"] = "拓海",
  [":hj_tuohai"] = "每回合限一次，你使用牌结算后，可以令一名角色选择一项：1、失去1点体力获得此牌。2、你摸两张牌。",
  ["#hj_tuohai-chooseTarget"] = "你可以发动“拓海”令一名角色失去体力获得此牌或令你摸牌。",
  ["#hj_tuohai-choose2get"] = "你可以失去一点体力获得此牌，或者点击取消令 孙登 摸两张牌。",
  ["hj_xingguo"] = "兴国",
  [":hj_xingguo"] = "每回合限一次，当你于摸牌阶段外获得牌后，你可以弃置至多X张牌并选择一名角色，其下个回合摸牌阶段多摸X张牌，出牌阶段可以多使用一张【杀】，手牌上限+1，则若其为你，你失去1点体力（X为你体力数与手牌数差值且至少为1）。",
  ["#hj_xingguo-use"] = "你可以发动“兴国”，弃置至多%arg张牌",
  ["@@hj_xingguo-turn"] = "兴国",
  ["@@hj_xingguo"] = "兴国",
  ["hj_xuanhe"] = "宣和",
  [":hj_xuanhe"] = "主公技，锁定技，出牌阶段开始时，若你手牌数不大于/不小于X，则你你获得“制衡”/“激昂”直到你下次发动此技能（X为场上吴势力角色数）。"
}


return extension